#include "../logs/log.h"

enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

//用户可以通过自己实现一个文件滚动方式，基础logsink父类即可使用

//以时间间隔进行文件滚动
class RollByTimeSink : public Hxy_Log::LogSink
{
public:
    // 需要传入指定文件的文件路径,并打开文件，把操作句柄管理起来
    RollByTimeSink(const std::string &basename,TimeGap gap_type)
        :_basename(basename)
    {
        switch (gap_type)
        {
            case TimeGap::GAP_SECOND : _gap_size = 1;break;
            case TimeGap::GAP_MINUTE : _gap_size = 60;break;
            case TimeGap::GAP_HOUR : _gap_size = 3600;break;
            case TimeGap::GAP_DAY : _gap_size = 3600*24;break;
        }
        _cur_gap = _gap_size == 1?Hxy_Log::util::date::GetTime():Hxy_Log::util::date::GetTime()%_gap_size;
        std::string pathname = _CreateNewFile();
        Hxy_Log::util::file::CreateDirectory(Hxy_Log::util::file::Path(pathname));
        _ofs.open(pathname,std::ios::binary | std::ios::app);  
        assert(_ofs.is_open());
    }
    virtual void log(const char *data, size_t len)
    {
        size_t cur = Hxy_Log::util::date::GetTime();
        if(_cur_gap != cur%_gap_size)
        {
            _ofs.close();
            std::string pathname = _CreateNewFile();
            _ofs.open(pathname,std::ios::binary | std::ios::app);  
            assert(_ofs.is_open());
        }
        _ofs.write(data,len);
        assert(_ofs.good());
    }
private:
        std::string _CreateNewFile()
        {
            time_t t = Hxy_Log::util::date::GetTime();
            struct tm tm;
            localtime_r(&t,&tm);
            std::stringstream ss;
            ss<<_basename;
            ss<<tm.tm_year;
            ss<<tm.tm_mon;
            ss<<tm.tm_mday;
            ss<<tm.tm_hour;
            ss<<tm.tm_min;
            ss<<tm.tm_sec;
            ss<<".log";
            return ss.str();
        }

private:
    std::string _basename; // 文件路径名称
    std::ofstream _ofs;    // 操作句柄
    size_t _cur_gap;    //当前时间间隔
    size_t _gap_size;   //需要指定时间间隔大小
};

int main()
{
    std::unique_ptr<Hxy_Log::LoggerBuilder> ptr(new Hxy_Log::GlobalLoggerBuilder());
    ptr->BuildLoggerName("Async-logger");
    ptr->BuildLoggerType(Hxy_Log::LoggerType::ASYNCTYPE);
    ptr->BuildLoggerValue(Hxy_Log::LogLevel::value::WARN);
    ptr->BuildFormatter();
    ptr->BuildSink<Hxy_Log::StdOutSink>();
    ptr->BuildSink<Hxy_Log::FileSink>("./logfile/asyc.log");
    ptr->BuildSink<RollByTimeSink>("./logfile/roll-time-", TimeGap::GAP_SECOND);
    Hxy_Log::Logger::ptr logger = ptr->build();

    size_t old = Hxy_Log::util::date::GetTime();
    while(Hxy_Log::util::date::GetTime() < old + 5)
    {
        logger->fatal("%s","扩展按时间切换滚动文件...");
        usleep(1000);
    }

    return 0;
}